package salesforce;

import java.util.Arrays;

//LC 875

/**
 * 猩猩吃香蕉 二分
 */
public class KokoEatingBananas {
    public int minEatingSpeed(int[] piles, int h) {
        int l = 1;
        int r = maxPile(piles);
        while (l < r) {
            int mid = l + (r - l) / 2;
            if (eat(piles, mid) > h) {
                l = mid + 1;
            }else {
                r = mid; //这里不能-1
            }
        }
        return l; //TODO 记得不是返回中点而是返回左边界
    }

    private int maxPile(int[] piles) {
//        int res = 0;
//        for(int pile: piles) {
//            res = Math.max(res, pile);
//        }
//        return res;
        return Arrays.stream(piles).max().getAsInt();
    }

    private int eat(int[] piles, int speed) {
        int res = 0;
        for (int pile : piles) {
            res += (pile + speed - 1) / speed; //向上取整
        }
        return res;
    }
}
